/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExCoUpPanel.java
 *
 * Created on 01/12/2011, 01:53:19
 */
package proj5labbd.graphics.exibicaoComercial;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class ExCoUpPanel extends OperationPanel {

    /** Creates new form ExCoUpPanel */
    public ExCoUpPanel(ExCoFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtUpdate.addActionListener(new ExCoAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert1 = new javax.swing.JPanel();
        jlbDate1 = new javax.swing.JLabel();
        jlbInicio1 = new javax.swing.JLabel();
        jlbTermino1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbCliente = new javax.swing.JTable();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jftxtDate = new javax.swing.JFormattedTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbUpdate = new javax.swing.JTable();
        jbtUpdate = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert1.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de atualização"));

        jlbDate1.setText("Data de exibição");

        jlbInicio1.setText("Horário de início");

        jlbTermino1.setText("Horário de término");

        jLabel2.setText("Cliente");

        jtbCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbCliente);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnInsert1Layout = new javax.swing.GroupLayout(jpnInsert1);
        jpnInsert1.setLayout(jpnInsert1Layout);
        jpnInsert1Layout.setHorizontalGroup(
            jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsert1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGroup(jpnInsert1Layout.createSequentialGroup()
                        .addGroup(jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbDate1)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbInicio1)
                            .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpnInsert1Layout.createSequentialGroup()
                                .addComponent(jlbTermino1)
                                .addGap(50, 50, 50))
                            .addComponent(jftxtFim, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jpnInsert1Layout.setVerticalGroup(
            jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsert1Layout.createSequentialGroup()
                .addComponent(jlbDate1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnInsert1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnInsert1Layout.createSequentialGroup()
                        .addComponent(jlbTermino1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpnInsert1Layout.createSequentialGroup()
                        .addComponent(jlbInicio1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(12, 12, 12)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtbUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbUpdate);

        jbtUpdate.setText("Atualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnInsert1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jbtUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(jbtUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents
    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados das tabelas");
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Trata eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbCliente.clearSelection();
        jtbUpdate.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtUpdate;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbDate1;
    private javax.swing.JLabel jlbInicio1;
    private javax.swing.JLabel jlbTermino1;
    private javax.swing.JPanel jpnInsert1;
    private javax.swing.JTable jtbCliente;
    private javax.swing.JTable jtbUpdate;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata as tabelas cliente e exibicaoComercial para serem exibidas
     */
    private void setupTable() throws SQLException {
        
        String [] titlesCl = {"CNPJ","Razão Social","Nome Fantasia"};
        String [] fieldsCl = {"cliente.cnpjCl","cliente.nomeCompletoCl","cliente.nomeFantasiaCl"};
        String [] paramsCl = {};
        String [][] sCl = dbInterface.view(fieldsCl, paramsCl, new String[]{"cliente"});
        
        DefaultTableModel model = new DefaultTableModel(sCl,titlesCl);
        jtbCliente.setModel(model);
        
        String [] fieldsExCo = {"exibicaoComercial.idPr","exibicaoComercial.dataExCo","exibicaoComercial.horaInicioExCo",
            "exibicaoComercial.horaFimExCo","exibicaoComercial.precoExCo","exibicaoComercial.cnpjCl"
        };
        String [] titlesExCo = {"ID Comercial","Data","Hora Início",
            "Hora Fim","Preço","CNPJ"
        };
        String [] paramsExCo = {
            "exibicaoComercial.idPr=comercial.idPr","exibicaoComercial.cnpjCl=cliente.cnpjCl"
        };
        
        String [][] sExCo = dbInterface.view(fieldsExCo, paramsExCo, new String[]{"exibicaoComercial","comercial","cliente"});
        
        model = new DefaultTableModel(sExCo,titlesExCo);
        jtbUpdate.setModel(model);
        
    }
    
    class ExCoAction implements ActionListener {
        
        /*
         * Controla os eventos de inserção
         */
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtbCliente.getSelectedRowCount() == 1) {
                fields.add("exibicaoComercial.cnpjCl='"+jtbCliente.getValueAt(jtbCliente.getSelectedRow(), 0)+"'");
            }
            
            if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                fields.add("exibicaoComercial.dataExCo="+"TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
            }
            if (jftxtIni.getText().compareTo("  :  ") != 0) {
                fields.add("exibicaoComercial.horaInicioExCo='"+jftxtIni.getText()+"'");
            }
            if (jftxtFim.getText().compareTo("  :  ") != 0) {
                fields.add("exibicaoComercial.horaFimExCo='"+jftxtFim.getText()+"'");
            }
            
            if (fields.size() > 0 && jtbUpdate.getSelectedRowCount() > 0) {
                String [] params = new String[3];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtbUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        params[0] = "exibicaoComercial.idPr="+jtbUpdate.getValueAt(rows[i],0).toString();
                        params[1] = "exibicaoComercial.dataExCo=TO_DATE('"+
                                jtbUpdate.getValueAt(rows[i],1).toString().substring(0,10) +"','YYYY-MM-DD')";
                        params[2] = "exibicaoComercial.horaInicioExCo"
                                + "='"+jtbUpdate.getValueAt(rows[i], 2)+"'";
                        dbInterface.update(fieldsArray, params, new String[]{"exibicaoComercial"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtbUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }

}